/*
 * @Description:menu Server
 * @Version: 2.0
 * @Autor: kafei
 * @Date: 2021-12-07 17:46:20
 * @LastEditors: kafei
 * @LastEditTime: 2021-12-21 15:23:23
 */
const execSQL = require('../db/connect')
const { createInsertSql } = require('../utils/sql')
async function allMenuServer() {
  const sql = `select * from dy_tmenu`
  const result = await execSQL(sql)
  return result
}
function updateSql(targetTable, data, target = 'id') {
  let str = ''
  const keys = Object.keys(data)
  for (let i = 0; i < keys.length; i++) {
    const targetKey = keys[i]
    if (targetKey !== target) {
      str += `${targetKey}= '${changeTypeData(data[targetKey]) ? data[targetKey] : ''}',`
    }
  }
  const resultStr = str.substring(0, str.length - 1)
  const sql = `UPDATE ${targetTable} SET ${resultStr} WHERE ${target} = '${data[target]}';`
  return sql
}

function changeTypeData(data) {
  if (data === undefined || data === null) {
    return false
  }
  return true
}

async function updateMenuServer(res) {
  const sql = updateSql('dy_tmenu', res)
  const result = await execSQL(sql)
  return result
}

async function getMenuByIdServer(id) {
  const sql = `select * from dy_tmenu where id='${id}'`
  const result = await execSQL(sql)
  return result
}

async function addMenuServer(res) {
  const sql = createInsertSql('dy_tmenu', res)
  const result = await execSQL(sql)
  return result
}

async function delMenuServer(res) {
  const { id } = res
  const sql = `DELETE FROM dy_tmenu WHERE id=${id};`
  const result = await execSQL(sql)
  return result
}

module.exports = {
  allMenuServer,
  updateMenuServer,
  getMenuByIdServer,
  addMenuServer,
  delMenuServer
}
